package com.crishne.anwo.controller;

import com.alibaba.fastjson.JSONObject;
import com.crishne.anwo.config.ConfigInfo;
import com.crishne.anwo.constant.JsonStringConstant;
import com.crishne.anwo.dto.Pager;
import com.crishne.anwo.model.Content;
import com.crishne.anwo.service.ContentService;
import com.crishne.anwo.service.LogService;
import com.crishne.anwo.utill.CommonUtill;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("content/")
public class ContentController {
	
	@Autowired
	private ContentService contentService;

	@Autowired
	private ConfigInfo configInfo;

	@Autowired
	private LogService logService;
	
	private CommonUtill commonUtill = new CommonUtill();



	//返回jsp视图
	@RequestMapping(value = "mainpage_main")
	public String user_main(){
		return "admin/mainpage/mainpage_main";
	}
	
	
	@RequestMapping("getContentPageList")
	public void getContentPageList(HttpServletResponse response,HttpServletRequest request){
		//获取当前页 和 一页显示的数据数目
		String conCurrentPage = request.getParameter("currentpage");
		String stPageSize = request.getParameter("pageSize");
		String stContentName = request.getParameter("contentName");
//        String searchStatus = request.getParameter("searchStatus");
//        String searchType = request.getParameter("searchType");

		Integer currentpage = 1;
		Integer pageSize = 10;
		if(conCurrentPage != null && !"".equals(conCurrentPage)){
			currentpage = Integer.valueOf(conCurrentPage);
		}
		
		if(stPageSize != null && !"".equals(stPageSize)){
			pageSize = Integer.valueOf(stPageSize);
		}
		
		
		Content searchCountry = new Content();
		if(null != stContentName && !"".equals(stContentName)){
            searchCountry.setStContentName(stContentName);
        }
//        if(null != searchStatus && !"".equals(searchStatus)){
//            searchCountry.setStStatus(searchStatus);
//        }
//        if(null != searchType && !"".equals(searchType)){
//            searchCountry.setStTypeId(searchType);
//        }
        searchCountry.setStIfRemoved("0");
		Pager countryPageList = contentService.findPageList(searchCountry, currentpage, pageSize);
		JSONObject jsonString = JsonStringConstant.getSuccessMessage(countryPageList);

		commonUtill.OutputJson(jsonString, response, request);
    }

	/**
	 * 添加或修改内容页面
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping("mainpage_add")
	public String  mainpage_add(HttpServletResponse response, HttpServletRequest request, Model model)
	{
		String contentId = request.getParameter("contentId");
		Content tContent = null;
		if (null != contentId && !"".equals(contentId)){
			tContent = contentService.getById(contentId);
		}

		model.addAttribute("tContent",tContent);
		model.addAttribute("contentId",contentId);
		return "admin/mainpage/mainpage_add";
	}
    
    @RequestMapping("saveOrEditContent")
	public String  saveOrEditContent(HttpServletResponse response,HttpServletRequest request){
		HttpSession session = request.getSession();
		String userId = (String)session.getAttribute("userid");
		String stUserName = (String)session.getAttribute("username");

		String contentId = request.getParameter("contentId");
		String stTypeId = request.getParameter("stTypeId");
		String stContentName = request.getParameter("stContentName");
		String nmOrder = request.getParameter("nmOrder");

		String content = request.getParameter("content");

		Content tContent = new Content();

		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		try {
			if (multipartResolver.isMultipart(request)) {
				//获取上传路径配置
				String contentimgpath = request.getSession().getServletContext().getRealPath(configInfo.getContentImg())+ File.separator;
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				Iterator<String> iter = multiRequest.getFileNames();
				while (iter.hasNext()) {
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {
						String attId = UUID.randomUUID().toString();
						// 文件名
						String myFileName = file.getOriginalFilename();
						if (myFileName.trim() != "") {
							String fileName = file.getOriginalFilename();
							String fileExt = fileName.substring(
									fileName.lastIndexOf(".") + 1).toLowerCase();

							tContent.setStLogoUrl(attId + "." + fileExt);

							String upLoadPath = contentimgpath + attId + "." + fileExt;//上传路径
							File localFile = new File(upLoadPath);
							if (!localFile.exists()) {// 如果文件夹不存在，自动创建
								localFile.mkdirs();
							}
							file.transferTo(localFile);
						}
					}
				}
			}

		}catch(Exception e) {
			e.printStackTrace();
		}

		if(null == contentId || "".equals(contentId)){
			tContent.setStContentId(UUID.randomUUID().toString());
			tContent.setStIfRemoved("0");
			tContent.setDtCreate(new Date());
			tContent.setStCreaterId(userId);
		}
		else{
			tContent = contentService.getById(contentId);
			tContent.setDtUpdate(new Date());
			tContent.setStUpdaterId(userId);
		}

		tContent.setStContentName(stContentName);
		tContent.setStTypeId(stTypeId);

		if(nmOrder != null && !"".equals(nmOrder)){
			tContent.setNmOrder(Integer.valueOf(nmOrder));
		}
		else{
			tContent.setNmOrder(9999);
		}
		tContent.setStContent(content);


		//保存信息
		if(null == contentId || "".equals(contentId)){
			contentService.save(tContent);

			//记录登录日志
			logService.logFao(request,"创建内容",stUserName+"内容标题："+tContent.getStContentName());
		}
		else{
			contentService.update(tContent);

			//记录登录日志
			logService.logFao(request,"修改内容",stUserName+"-内容标题："+tContent.getStContentName());
		}
		return "admin/mainpage/mainpage_main";
    }
    
    @RequestMapping("removeContent")
    public void removeContent(HttpServletResponse response,HttpServletRequest request){
    	String stIds = request.getParameter("stIds");
    	JSONObject jsonString = new JSONObject();
    	try{
    		if(null != stIds && !"".equals(stIds)){
				HttpSession session = request.getSession();
				String userId = (String)session.getAttribute("userid");

    			String[] ids = stIds.split(",");
    			for(int i=0 ;i<ids.length;i++){
    			    if(null != ids[i] && !"".equals(ids[i])){
                        Content tContent = new Content();
                        tContent.setStContentId(ids[i]);
                        tContent.setStIfRemoved("1");
                        tContent.setDtRemoved(new Date());
                        tContent.setStRemoverId(userId);
                        contentService.remove(tContent);
                    }
    			}
        		jsonString = JsonStringConstant.getNoDataSuccessMessage("删除成功！");
    		}
    		else{
    			jsonString = JsonStringConstant.getNoDataSuccessMessage("删除失败！");
    		}
    	}
    	catch(Exception ex){
    		jsonString = JsonStringConstant.getNoDataSuccessMessage("删除失败！");
    	}
    	
		commonUtill.OutputJson(jsonString, response, request);
    }

}